import "@/index.css";
import { useState } from "react";
import { Input } from "antd";

const { TextArea } = Input;

function convertImageToBase64(
  file: File,
  callback: (base64String: string) => void
) {
  const reader = new FileReader();
  reader.onload = function (event) {
    // 获取Base64编码的图片数据
    const base64String = event?.target?.result as string;
    callback(base64String || "");
  };
  reader.readAsDataURL(file); // 将文件读取为Data URL（Base64编码）
}

export const ImgAndBase64Convert = ({ base64 }: { base64: string }) => {
  const [base64String, setBase64String] = useState(base64);
  const changeHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event?.target?.files?.[0];
    if (file) {
      convertImageToBase64(file, (base64String: string) => {
        console.log(base64String);
        setBase64String(base64String);
      });
    }
  };
  return (
    <div className="flex flex-col items-center justify-center gap-2">
      <div className="font-bold">图片和base64互转</div>
      <div className="flex flex-col gap-2">
        <div className="flex gap-2">
          <div className="w-[120px]">图片转base64</div>
          <Input
            type="file"
            className="w-[200px] h-[200px]"
            onChange={changeHandler}
          />
          <img
            className="w-[200px] h-[200px] bg-contain"
            src={base64String}
            alt="图片"
          />
        </div>
        <div className="flex gap-2">
          <div className="w-[120px]">base64转成图片</div>
          <TextArea
            className="w-[600px] h-[300px]"
            value={base64String}
            placeholder="这里是base64编码"
            onChange={(e) => setBase64String(e.target.value)}
            allowClear
          />
        </div>
      </div>
    </div>
  );
};
